import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/loginVue.vue'
import Register from '../views/registerVue.vue'
import Layout from '../views/layoutVue.vue'
import Collect from '../views/collectVue.vue'
import Hire from '../views/hireVue.vue'
import cityList from '../views/cityList.vue'

// 二级路由
import Looking from '../views/LookingVue.vue'
import Looking2 from '../views/Looking2Vue.vue'
import Looking3 from '../views/Looking3Vue.vue'
import Looking4 from '../views/Looking4Vue.vue'
import Looking5 from '../views/Looking5Vue.vue'

import { getToken } from '@/utils/storage'
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    { path: '/register', component: Register },
    { path: '/collect', component: Collect },
    { path: '/hire', component: Hire },
    { path: '/citylist', component: cityList },
    {
      path: '/',
      component: Layout,
      redirect: '/looking',
      children: [
        { path: '/looking', component: Looking },
        { path: '/looking2', component: Looking2 },
        { path: '/looking3', component: Looking3 },
        { path: '/looking4', component: Looking4 },
        { path: '/looking5', component: Looking5 }
      ]
    }
  ]
})

// 白名单
const whiteList = ['/login', '/register']
// to:去哪里 from:从哪里来； next 是一个函数， 调用next 表示放行
router.beforeEach((to, from, next) => {
  const token = getToken()
  if (token) {
    next() // 如果有token，直接放行
  } else {
    // 判断是否在白名单
    if (whiteList.includes(to.path)) {
      next() // 如果在白名单，就放行
    } else {
      next('/login')
    }
  }
})

export default router
